package com.atnjupt.servlet;
/**
 * @author Wizarder
 * @create 2021-06-03 12:03
 */

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class Upload extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1 先判断上传的数据是否多段数据（只有是多段的数据，才是文件上传的）
        if (ServletFileUpload.isMultipartContent(request)) {
            //创建FileItemFactory工厂实现类
            FileItemFactory fif = new DiskFileItemFactory();
            // 创建用于解析上传数据的工具类ServletFileUpload类
            ServletFileUpload sfu = new ServletFileUpload(fif);//要创建文件工厂不然报异常No FileItemFactory has been set.
            // 解析上传的数据，得到每一个表单项FileItem
            try {
                List<FileItem> list = sfu.parseRequest(request);
                // 循环判断，每一个表单项，是普通类型，还是上传的文件
                for (FileItem item : list) {
                    if (item.isFormField()) {
                        // 普通表单项
                        System.out.println("表单项的name属性值：" + item.getFieldName());
                        System.out.println("表单项的value属性值：" + item.getString());
                    }else{
                        // 上传的文件
                        System.out.println("表单项目name属性值：" + item.getFieldName());
                        System.out.println("上传的文件名：" + item.getName());

                        item.write(new File("G:\\" + item.getName()));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
